<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "../private/login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "../private/login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php require_once('../Connections/miportal.php');
mysql_query("SET NAMES 'utf8'"); ?>
<?php

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

//$colname_rs = "-1";
//if (isset($_GET['$_POST['insCURP']'])) {
//  $colname_rs = $_GET['$_POST['insCURP']'];
//}
//mysql_select_db($database_miportal, $miportal);


$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_SELECT_IES"])) && ($_POST["MM_SELECT_IES"] == "formSelectIES")) {
	
	$updateSql = sprintf("Update cat_ies SET nb_domicilio= %s WHERE id_cat_ies= %s AND nb_domicilio IS NULL",
                       GetSQLValueString($_POST['insDireccion'], "text"),
                       GetSQLValueString($_POST['insIES'],"int"));
					   
  mysql_select_db($database_miportal, $miportal);
  $updateIES = mysql_query($updateSql, $miportal) or die(mysql_error());
	
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formRegCandidato")) {
$convocatoria_activa=NULL;

			if($_SESSION['MM_tp_programa']=="EMPLEATE"){$convocatoria_activa=23;}else 
			if($_SESSION['MM_tp_programa']=="EXPERIMENTA"){$convocatoria_activa=22;}else 
			{echo "-1";}	
	
	
  $insertSQL = sprintf("INSERT INTO cor_candidato (id_cve_curp, nb_nom_nombre1, nb_nom_nombre2, nb_nom_apaterno, nb_nom_amaterno, tp_stat_registro, id_cat_ies,id_convocatoria_activa,tp_status) VALUES (%s, %s, %s, %s, %s,%s,%s,%s,%s)",
                       GetSQLValueString($_POST['insCURP'], "text"),
                       GetSQLValueString($_POST['insNombre'], "text"),
                       GetSQLValueString($_POST['insNombres'], "text"),
                       GetSQLValueString($_POST['insPaterno'], "text"),
                       GetSQLValueString($_POST['insMaterno'], "text"),
					   GetSQLValueString(1, "int"), //
					   GetSQLValueString($_POST['id_ies'], "int"),//Esta es la IES, se debe cambiar por variable de sesión del RIV,ROV [id_target]
					   GetSQLValueString($convocatoria_activa, "int"),
					   GetSQLValueString(2, "int"));//Esta el estatus de registro, 0 es para Externos(Aun no esta disponible), 1 es para DVA y 2 para DVE
  mysql_select_db($database_miportal, $miportal);
  $Result1 = mysql_query($insertSQL, $miportal) or die(mysql_error());

  $insertGoTo = "form_dve_cand_expediente.php";
  
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  //INICIO DEL SELECT PARA OBTENER DATOS DE REGISTRO
$name=$_POST['insNombre']." ".$_POST['insNombres']." ".$_POST['insPaterno']." ".$_POST['insMaterno'];
  $query_rs = sprintf("SELECT id_cor_candidato, id_cve_curp, nb_nom_nombre1, nb_nom_nombre2, nb_nom_apaterno, nb_nom_amaterno,id_cat_ies FROM cor_candidato WHERE id_cve_curp = %s", GetSQLValueString($_POST['insCURP'], "text"));
$rs = mysql_query($query_rs, $miportal) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);
$totalRows_rs = mysql_num_rows($rs);
  //FIN DEL SELECT LO ENVIAMOS EN HEAFES BY POST
  header(sprintf("Location: %s", $insertGoTo."user=".base64_encode($row_rs['id_cor_candidato'])."&name=".base64_encode($name)."&ies=".base64_encode($row_rs['id_cat_ies'])));
  
}
?>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximun-scale=1">
<title>FUNDACIÓN EDUCACIÓN SUPERIOR-EMPRESA</title>
<!--Hoja de estilo principal-->
<link href="../css/styletd2.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> 
<link rel="stylesheet" type="text/css" href="../css/mos-style.css">
<link rel="stylesheet" type="text/css" href="../css/menu.css"><!--Pemanggilan gambar favicon-->
 <!--pemanggilan file css-->
<script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css">
<script language=""="JavaScript">
	function conMayusculas(field) {
				field.value = field.value.toUpperCase()
		}
			function incubadora(val) {
				documen.write(val);
		}
	function MM_jumpMenu(targ,selObj,restore){ //v3.0
	  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	  if (restore) selObj.selectedIndex=0;
	}

	function confirmar ( mensaje ) {
					return confirm( mensaje );
				}
        </script>
<script language=""="JavaScript">
function validaCURP(curp){

	var reg = "";
	
	if(curp.length == 18)
	{
		var digito = calculaDigito(curp);
		
		reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}[B-DF-HJ-NP-TV-Z]{3}[A-Z0-9][0-9]/;

		if(curp.search(reg))
		{
			alert("La curp: " + curp + " no es valida, verifiqué ");
			return false;
			
		}
		
		if(!(parseInt(digito) == parseInt(curp.substring(17,18))))
		{
			alert("La curp: " + curp + " no es valida, revisé el Digito Verificador (" +  digito + ")");
			return false;
		}
		return true;
	}
	else
	{
		switch (curp.length) 
		{
			case 10 :
				reg = /[A-Z]{4}\d{6}/;
				break;
			case 11 :
				reg = /[A-Z]{4}\d{6}[HM]/;
				break;
			case 12 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]/;
				break;
			case 13 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}/;
				break;
			case 14 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}[B-DF-HJ-NP-TV-Z]/;
				break;
			case 15 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}[B-DF-HJ-NP-TV-Z]{2}/;
				break;
			case 16 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}[B-DF-HJ-NP-TV-Z]{3}/;
				break;
			case 17 :
				reg = /[A-Z]{4}\d{6}[HM][A-Z]{2}[B-DF-HJ-NP-TV-Z]{3}[A-Z0-9]/;
				break;
		}
	
		if(curp.search(reg))
		{
			alert("La curp: " + curp + " no es valida, verifiqué ");
			return false;
		}
		return true;
	}
}

/* ******************************************************************************************* */
function calculaDigito(curp){
	var segRaiz      = curp.substring(0,17);
	var chrCaracter  = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
	var intFactor    = new Array(17);
	var lngSuma      = 0.0;
	var lngDigito    = 0.0;
	
	for(var i=0; i<17; i++)
	{
		for(var j=0;j<37; j++)
		{
			if(segRaiz.substring(i,i+1)==chrCaracter.substring(j,j+1))
			{  				
				intFactor[i]=j;
			}
		}
	}
	
	for(var k = 0; k < 17; k++)
	{
		lngSuma= lngSuma + ((intFactor[k]) * (18 - k));
	}
	
	lngDigito= (10 - (lngSuma % 10));
	
	if(lngDigito==10)
	{
		lngDigito=0;
	}

	return lngDigito;
}
</script>
</head>
<body>

<div id="background">
</div>

 
<header>
        <div id="background"></div><!--BackGround Menu header-->
		<div class="img_header_logo"></div>
		<span class="img_header_logo"><a href="http://fese.org.mx"><img src="../images/fese/FESE_home_logo.png"  height="90" alt="FESE" align="bottom" /></a></span>
		<div class="img_header_logo"></div>
		<?php include_once('../include/dve_nav.php');?>
</header>

<center>
<div id="boxcontainer">
<div id="container">
<form action="<?php echo $editFormAction; ?>" method="POST" name="formRegCandidato">
<table name="t_candidato" min-width="620px" border="1" style="margin:0 auto; padding-left:5%;">
	<tr>
	  <td colspan="2">&nbsp;</td>
	  </tr>
	<tr>
		<td colspan="2"><h3 style="text-align:left; margin-left:-20px;">DATOS PERSONALES DEL CANDIDATO  
		  <input type="hidden" name="id_ies" id="id_ies" value="<?php if(isset($_POST['insIES'])){echo $_POST['insIES'];}?>">
		  <input type="hidden" name="direccion_ies" id="direccion_ies" value="<?php if(isset($_POST['insDireccion'])){echo $_POST['insDireccion'];}?>">
		</h3></td>
		</tr>
	<tr>
		<td>CURP*</td>
		<td><span id="curp">
        <input name="insCURP" type="text" id="insCURP" style="width:280px" onChange="conMayusculas(this)"  onBlur="validaCURP(this.value)"  size="18" maxlength="18">
        <br>
        <span class="textfieldRequiredMsg">Se necesita un valor.</span><span class="textfieldMinCharsMsg">No se cumple el mínimo de caracteres requerido.</span><span class="textfieldMaxCharsMsg">Se ha superado el número máximo de caracteres.</span></span></td>
	</tr>
	<tr>
		<td>Apellido Paterno*</td>
		<td ><span id="spryPaterno">
		  <input type="text" name="insPaterno" id="insPaterno" onChange="conMayusculas(this)" style="width:280px">
		  <span class="textfieldRequiredMsg">Se necesita un valor.</span></span></td>
	</tr>
	<tr>
		<td>Apellido Materno*</td>
		<td><span id="spryteMaterno">
		  <input type="text" name="insMaterno" id="insMaterno" onChange="conMayusculas(this)" style="width:280px">
		  <span class="textfieldRequiredMsg">Se necesita un valor.</span></span></td>
	</tr>
	<tr>
		<td>Primer Nombre*</td>
		<td><span id="spryteNombre">
		  <input type="text" name="insNombre" id="insNombre" onChange="conMayusculas(this)" style="width:280px">
		  <span class="textfieldRequiredMsg">Se necesita un valor.</span></span></td>
	</tr>
	<tr>
		<td>Segundo nombre</td>
		<td><input type="text" name="insNombres" id="insNombres" onChange="conMayusculas(this)" style="width:280px"></td>
	</tr>
	<tr>
	  <td colspan="2" style="text-align:right"><input type="submit" class="button" value="Guardar y continuar" onClick="return confirmar('¿Esta seguro que desea registrar los datos ingresados?')"></td>
	  </tr>
</table>
<input type="hidden" name="MM_insert" value="formRegCandidato">
</form>

</div><!--Container-->

<div id="rightContainer">
    <div id="Bienvenida">
    <div id="cuadro">
    <h1>Bienvenido</h1>
    </div>
    
    <div >
    <br>
            <?php echo $_SESSION['MM_UsName'] ?><br><br>
            <?php echo $_SESSION['MM_nmb_target'] ?><br>
            <a href="<?php echo $logoutAction ?>">Salir</a>
            </div>
    </div>
    <br style="clear:both"/>
    <div id="convocatoria">
    <div id="cuadro">
    <h1>Convocatoria</h1>
    </div>
    <br>
    <?php 
    if(isset($_SESSION['MM_tp_programa'])&$_SESSION['MM_tp_programa']=="Vigentes"){
        echo "<select name=\"slConvocatoria\">
        <option selected=\"selected\">Seleccione</option>
        <option value=\"empleate\">Empleate</option>
        <option value=\"experimenta\">Experimenta</option>
        <option value=\"mpe\">Mi Primera Empresa</option>
        <option value=\"vecas_vinculacion\">Vecas Vinculación</option>
        </select>
        "	;
    }else{
    echo $_SESSION['MM_tp_programa'];}
    ?>
    
    </div>
</div><!--contenedor derecho-->
  </div><!--boxcontainer-->
  
   
</center>
 <!-- <div id="Bienvenida">
<div id="cuadro">
<h1>Bienvenido</h1>
</div>

<div class="mosAdmin">-->
		<?php //echo $_SESSION['MM_UsName'] ?><!--<br>
    </div>
</div><!--Bien venida-->

<!--<br style="clear:both"/>



<div id="convocatoria">
<div id="cuadro">
<h1>Convocatoria</h1>
</div>


</div>--><!--Convocatoria-->
  <script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("curp", "none", {hint:"Curp a 18 caracteres", minChars:18, maxChars:18, validateOn:["blur", "change"]});
var sprytextfield2 = new Spry.Widget.ValidationTextField("spryPaterno", "none", {validateOn:["blur", "change"]});
var sprytextfield3 = new Spry.Widget.ValidationTextField("spryteMaterno", "none", {validateOn:["blur", "change"]});
var sprytextfield4 = new Spry.Widget.ValidationTextField("spryteNombre", "none", {validateOn:["blur", "change"]});
  </script>
</body>
</html>

